package bluetooth;

import entity.ExampleObject;
import java.io.IOException;
import java.io.OutputStream;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.obex.Operation;
import javax.obex.HeaderSet;
import javax.obex.ResponseCodes;
import javax.obex.ServerRequestHandler;
import javax.obex.SessionNotifier;
import visual.MidletVisual;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Developer
 */
public class BTObjectServer implements Runnable {

    private static final UUID OBJECT_EXCHANGER_UUID = new UUID("262242B3DADB9A41DE94C7C71CC3AB54", false);
    private String url;
    private MidletVisual parent;
    private boolean isBTReady;
    private LocalDevice localDevice;
    private SessionNotifier notifier;
    private ServiceRecord record;
    private RequestHandler handler;
    private ExampleObject sendable;

    public BTObjectServer(MidletVisual parent, ExampleObject sendable) {
        parent.printToFrm("Inicializando Servidor");
        this.sendable = sendable;
        this.parent = parent;

        handler = new RequestHandler();
        url = "btgoep://";
        url += "localhost:";
        url += OBJECT_EXCHANGER_UUID;
        url += ";name=Object Server";
        url += ";master=false";
        System.out.println(url);
        isBTReady = false;
    }

    public void run() {
        try {
            parent.printToFrm("Aguardando conexões...");
            localDevice = LocalDevice.getLocalDevice();
            notifier = (SessionNotifier) Connector.open(url);
            record = localDevice.getRecord(notifier);
            isBTReady = true;
            notifier.acceptAndOpen(handler); //abe o servidor com um ouvidor
            parent.printToFrm("Ouvidor incializado.");
        } catch (IOException ex) {
            parent.printToFrm("Nao foi possível completar inicialização: " + ex.getMessage());
        }
    }

    private class RequestHandler extends ServerRequestHandler {

        /**
         * Default constructor.
         */
        public RequestHandler() {
            //No implementation required. 
        }

        public int onGet(Operation op) {
            try {
                parent.printToFrm("Cliente solictou operação GET");
                System.out.println("Cliente solictou operação GET");
                OutputStream out = null;
                HeaderSet header = null;

                // criando um header para ser enviado ao cliente
                header = op.getReceivedHeaders();
                // adcionando os headers (infomações)
                // TYPE - represents obex message
                //header.setHeader(HeaderSet.NAME, "ExampleObject");
                // LENGTH - holds message length
                header.setHeader(HeaderSet.LENGTH, new Long(sendable.size()));
                header.setHeader(HeaderSet.DESCRIPTION,
                        sendable.getDescriptor());

                op.sendHeaders(header);

                System.out.println("Header enviado.");

                // Open the output stream to put the object to it
                out = op.openDataOutputStream();

                // Sending the object to client
                out.write(sendable.getBytes());
                out.flush();
                out.close();
                
            } catch (IOException ex) {
                parent.printToFrm(ex.getMessage());
            }
            return ResponseCodes.OBEX_HTTP_OK;
        }

        /**
         * From ServerRequestHandler.
         * Called when a DISCONNECT request is received.
         * @param request- contains the headers sent by the client; request 
         * will never be null
         * @param reply - the headers that should be sent in the reply;
         * reply will never be null
         */
        public void onDisconnect(HeaderSet request, HeaderSet reply) {
            parent.printToFrm("Desconectando...");
            //commandAction(cmdStop, frmMain);
        }

        public int onConnect(HeaderSet request, HeaderSet reply) {
            parent.printToFrm("Cliente connectando...");
            return ResponseCodes.OBEX_HTTP_OK;
        }
    }
}
